# -*- coding: utf-8 -*-  
'''
日志组件

@author: luoyi
Created on 2021年3月2日
'''
import yaml
import os
import sys


#    取项目根目录（其他一切相对目录在此基础上拼接）
ROOT_PATH = os.path.abspath(os.path.dirname(__file__)).split('nlp_seq2seq')[0]
ROOT_PATH = ROOT_PATH + "nlp_seq2seq"


#    取配置文件目录
CONF_PATH = ROOT_PATH + "/resources/conf.yml"
#    加载conf.yml配置文件
def load_conf_yaml(yaml_path=CONF_PATH):
    print('加载配置文件:' + CONF_PATH)
    f = open(yaml_path, 'r', encoding='utf-8')
    fr = f.read()
    
#     c = yaml.load(fr, Loader=yaml.SafeLoader)
    c = yaml.safe_load(fr)
    
    #    读取letter相关配置项
    dataset = Dataset(c['dataset']['in_train'], c['dataset']['count_train'], c['dataset']['label_train'],
                      c['dataset']['in_val'], c['dataset']['count_val'], c['dataset']['label_val'],
                      c['dataset']['in_test'], c['dataset']['count_test'], c['dataset']['label_test'],
                      c['dataset']['batch_size'],
                      c['dataset']['epochs'],
                      c['dataset']['shuffle_buffer_rate'])
    
    models = Models(c['models']['embedding_dims'],
                    c['models']['hidden_units'],
                    c['models']['learning_rate'],
                    c['models']['model_save_weights'],
                    c['models']['tensorboard_dir'])
    
    text = Text(c['text']['max_len'],
                c['text']['thesaurus'],
                c['text']['dictionaries_path'])
    
    return c, dataset, text, models


#    验证码识别数据集。为了与Java的风格保持一致
class Dataset:
    def __init__(self, 
                 in_train="", count_train=50000, label_train="",
                 in_val="", count_val=10000, label_val="", 
                 in_test="", count_test=10000, label_test="", 
                 batch_size=2, epochs=2, shuffle_buffer_rate=-1):
        self.__in_train = convert_to_abspath(in_train)
        self.__count_train = count_train
        self.__label_train = convert_to_abspath(label_train)
        
        self.__in_val = convert_to_abspath(in_val)
        self.__count_val = count_val
        self.__label_val = convert_to_abspath(label_val)
        
        self.__in_test = convert_to_abspath(in_test)
        self.__count_test = count_test
        self.__label_test = convert_to_abspath(label_test)
        
        self.__batch_size = batch_size
        self.__epochs = epochs
        self.__shuffle_buffer_rate = shuffle_buffer_rate
        pass
    def get_in_train(self): return convert_to_abspath(self.__in_train)
    def get_count_train(self): return self.__count_train
    def get_label_train(self): return convert_to_abspath(self.__label_train)
    
    def get_in_val(self): return convert_to_abspath(self.__in_val)
    def get_count_val(self): return self.__count_val
    def get_label_val(self): return convert_to_abspath(self.__label_val)
    
    def get_in_test(self): return convert_to_abspath(self.__in_test)
    def get_count_test(self): return self.__count_test
    def get_label_test(self): return convert_to_abspath(self.__label_test)
    
    def get_batch_size(self): return self.__batch_size
    def get_epochs(self): return self.__epochs
    def get_shuffle_buffer_rate(self): return self.__shuffle_buffer_rate
    pass


#    文本相关配置
class Text:
    def __init__(self,
                 max_len=20,
                 thesaurus=[],
                 dictionaries_path=''):
        self._max_len = max_len
        
        #    词库列表转换为系统绝对路径
        abs_thesaurus = []
        for thesauru in thesaurus:
            thesauru = convert_to_abspath('resources/thesaurus/' + thesauru)
            abs_thesaurus.append(thesauru)
            pass
        self._thesaurus = abs_thesaurus
        
        self._dictionaries_path = dictionaries_path        
        pass
    def get_max_len(self): return self._max_len
    def get_thesaurus(self): return self._thesaurus
    def get_dictionaries_path(self): return convert_to_abspath(self._dictionaries_path)
    pass


#    模型相关配置
class Models:
    def __init__(self,
                 embedding_dims=5,
                 hidden_units=4,
                 learning_rate=0.001,
                 model_save_weights='temp/models',
                 tensorboard_dir='logs/tensorboard'):
        self._embedding_dims = embedding_dims
        self._hidden_units = hidden_units
        self._learning_rate = learning_rate
        self._model_save_weights = model_save_weights
        self._tensorboard_dir = tensorboard_dir
        pass
    def get_embedding_dims(self): return self._embedding_dims
    def get_hidden_units(self): return self._hidden_units
    def get_learning_rate(self): return self._learning_rate
    def get_model_save_weights(self): return self._model_save_weights
    def get_tensorboard_dir(self): return convert_to_abspath(self._tensorboard_dir)
    pass


#    取配置的绝对目录
def convert_to_abspath(path):
    '''取配置的绝对目录
        "/"开头的目录原样输出
        非"/"开头的目录开头追加项目根目录
    '''
    if (path.startswith("/")):
        return path
    else:
        return ROOT_PATH + "/" + path
    
#    检测文件所在上级目录是否存在，不存在则创建
def mkfiledir_ifnot_exises(filepath):
    '''检测log所在上级目录是否存在，不存在则创建
        @param filepath: 文件目录
    '''
    _dir = os.path.dirname(filepath)
    if (not os.path.exists(_dir)):
        os.makedirs(_dir)
    pass
#    检测目录是否存在，不存在则创建
def mkdir_ifnot_exises(_dir):
    '''检测log所在上级目录是否存在，不存在则创建
        @param dir: 目录
    '''
    if (not os.path.exists(_dir)):
        os.makedirs(_dir)
    pass


#    写入配置文件
def write_conf(_dict, file_path):
    '''写入当前配置项的配置文件
        @param dict: 要写入的配置项字典
        @param file_path: 文件path
    '''
    file_path = convert_to_abspath(file_path)
    mkfiledir_ifnot_exises(file_path)
    
    #    存在同名文件先删除
    if (os.path.exists(file_path)):
        os.remove(file_path)
        pass
    
    fw = open(file_path, mode='w', encoding='utf-8')
    yaml.safe_dump(_dict, fw)
    fw.close()
    pass


#    追加sys.path
def append_sys_path(path):
    path = convert_to_abspath(path)
    sys.path.append(path)
    print(sys.path)
    pass



ALL_DICT, DATASET, TEXT, MODELS = load_conf_yaml()


